class Project < ActiveRecord::Base
  set_table_name "project"
  set_primary_key "project_id"

  has_many :users,
           :class_name  => 'UserProject',
	   :foreign_key => 'project_fk';

  has_many :comments,
           :class_name  => 'Comment',
	   :foreign_key => 'project_fk';

  has_many :tasks,
           :class_name  => 'Task',
	   :foreign_key => 'project_fk';

 has_many :iterations,
           :class_name  => 'Iteration',
	   :foreign_key => 'project_fk';


  validates_presence_of :name, :client_name, :description, :is_open;
  validates_uniqueness_of :name;

  def self.opened_projects
      return find(:all,
                  :conditions => ["is_open = ?",1]);
  end
 
  def opened
      return find(:all,
                  :conditions => ["is_open = ?",1]);
  end
 
  def self.closed_projects
      return find(:all,
                  :conditions => ["is_open = ?",0]);
  end

  # task statistics
  def task_statistics
      new_tasks = tasks.find(:all, 
                             :conditions => ["status_fk = ?",1]).size();
      opened_tasks = tasks.find(:all, 
                                :conditions => ["status_fk = ?",2]).size();
      stalled_tasks = tasks.find(:all, 
                                 :conditions => ["status_fk = ?",4]).size();

      return {:new => new_tasks, :opened => opened_tasks, :stalled => stalled_tasks};        
  end

  def active_tasks
      return tasks.find(:all,
                        :conditions => ['status_fk = ? or status_fk = ?',1,2] , 
                        :order      => 'created desc');
  end


  # get project
  # returns the project based on project id
  
  def self.get_project(project_id)
      return nil unless project_id;
      return find(:first,
                  :conditions => ["project_id = ?", project_id]);
  end

end
